define(function(require) {
    "use strict";
    var ko = require("knockout");
    var router = require("plugins/router");
    var layui = require("layui");
    var $ = require("jquery");
    var system = require("durandal/system");
    var isFinishTableTemp = require("text!./is-finish-table-temp.html");
    var isErrorTableTemp = require("text!./is-error-temp.html");
    var singleReviewTemp = require("text!./single-review-temp.html");
    var shareUrlContent = require("text!./share-url-content.html");

    var dateFtt = function(fmt, date) { //author: meizz
        var o = {
            "M+": date.getMonth() + 1, //月份
            "d+": date.getDate(), //日
            "h+": date.getHours() % 12 == 0 ? 12 : date.getHours() % 12, //小时
            "H+": date.getHours(), //小时
            "m+": date.getMinutes(), //分
            "s+": date.getSeconds(), //秒
            "q+": Math.floor((date.getMonth() + 3) / 3), //季度
            "S": date.getMilliseconds() //毫秒
        };
        if(/(y+)/.test(fmt))
            fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
        for(var k in o)
            if(new RegExp("("+ k +")").test(fmt))
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
        return fmt;
    };

    var acceptPageSize = [10, 30, 60, 90, 150, 300];
    var param = {
        wildcardSource: ko.observable(""),
        termSource: ko.observable(""),
        searchDate: ko.observable(""),
        actionId: ko.observable(""),
        /*hostExclude: ko.observable(""),
        protocolInclude: ko.observable(""),
        protocolExclude: ko.observable(""),
        refererFilter: ko.observable(""),
        targetFilter: ko.observable(""),
        minSize: ko.observable("-1"),*/
        curr: 1,
        limit: acceptPageSize[0]
    };

    var tableModel = {
        id: "account-list",
        elem: "#list-table", //指定原始表格元素选择器（推荐id选择器）
        height: "full-227", //容器高度
        cols: [[
            //标题栏
            { title: "操作", width: 90, templet: singleReviewTemp },
            { field: "status", title: "状态码", width: 80 },
            { title: "请求耗时", width: 94, templet: function(d) {
                return d.wasteTime + "ms";
            }  },
            { field: "url", title: "目标链接", width: 500 },
            { field: "host", title: "主机头", width: 200 },
            { field: "protocol", title: "协议", width: 80 },
            { field: "contentType", title: "ContentType", width: 120 },
            { title: "大小", width: 120, templet: function(d) {
                if (d.contentLength !== null) {
                    if (d.contentLength < 1024 * 1024) {
                        var num = d.contentLength / 1024;
                        return parseInt(num * 1000) / 1000 + "KB";
                    } else {
                        var num = d.contentLength / 1024 / 1024;
                        return parseInt(num * 1000) / 1000 + "MB";
                    }
                } else {
                    return "未知";
                }
            } },
            { title: "是否完成", width: 120, templet: isFinishTableTemp },
            { title: "是否报错", width: 120, templet: isErrorTableTemp },
            { field: "deep", title: "深度", width: 80 },
            //{ field: "requestTime", title: "请求时间", width: 170 }
            { title: "请求时间", width: 276, templet: function(d) {
                return new Date(d.requestTime).toString();
            } }
        ]], //设置表头
        url: "/back/test03",
        page: {
            limits: acceptPageSize/*,
            limit: param.limit,
            curr: param.curr*/
        },
        done: function(res, curr, count) {
            //设置当前页码
            param.curr = curr;
            //设置当前分页大小
            param.limit = tableIns.config.limit;
        },
        response: {
            statusCode: 200
        }
    };

    var tableIns = null;

    var modelId = null;
    var currentAction = ko.observable(null);

    return {
        activate: function(id, queryParam) {
            //重置部分参数防止缓存
            param.actionId("");
            param.searchDate("");

            modelId = id;
            if (!((typeof queryParam === "object") && queryParam)) {
                queryParam = { };
            }
            if ((typeof queryParam.actionId === "string") && queryParam.actionId) {
                param.actionId(queryParam.actionId);
            } else {
                if ((typeof queryParam.searchDate === "string") && queryParam.searchDate) {
                    param.searchDate(queryParam.searchDate);
                } else {
                    param.searchDate(dateFtt("yyyy-MM-dd HH:mm:ss", new Date()));
                }
            }
            if ((typeof queryParam.term === "string") && queryParam.term) {
                param.termSource(queryParam.term);
            } else {
                param.termSource("");
            }
            if ((typeof queryParam.wildcard === "string") && queryParam.wildcard) {
                param.wildcardSource(queryParam.wildcard);
            } else {
                param.wildcardSource("");
            }

            var promise = null;
            if (param.actionId()) {
                promise = $.ajax({
                    type: "get",
                    url: "/back/actionById/" + param.actionId(),
                    dataType: "json"
                }).then(function(response) {
                    currentAction(response.data);
                }, function(data) {
                    layui.use(["layer"], function() {
                        var layer = layui.layer;
                        layer.alert(data.responseJSON.msg);
                    });
                });
            } else {
                promise = $.ajax({
                    type: "get",
                    url: "/back/actionByTime",
                    dataType: "json",
                    data: { time: encodeURIComponent(param.searchDate()), planId: modelId }
                }).then(function(response) {
                    currentAction(response.data);
                }, function(data) {
                    layui.use(["layer"], function() {
                        var layer = layui.layer;
                        layer.alert(data.responseJSON.msg);
                    });
                });
            }
            return promise;
        },
        param: param,
        currentAction: currentAction,
        compositionComplete: function() {
            layui.use(["laytpl", "table", "element", "layer", "laydate", "form"], function() {
                var laytpl = layui.laytpl;
                var table = layui.table;
                var element = layui.element;
                var layer = layui.layer;
                var laydate = layui.laydate;
                var form = layui.form;

                $("#share-url").click(function() {
                    var url = "http://" + window.location.host + "/kunlunAssets/index.html#plan/trace/" + modelId + "?term=" + encodeURIComponent(param.termSource()) + "&wildcard=" + encodeURIComponent(param.wildcardSource()) + "&searchDate=" + encodeURIComponent(param.searchDate()) + "&actionId=" + encodeURIComponent(param.actionId());
                    layer.open({
                        content: shareUrlContent,
                        shadeClose: true,
                        btn: [],
                        title: "请复制",
                        success: function(layero, index) {
                            var inputDom = $(layero.selector).find(".share-url-input");
                            inputDom.val(url);
                            inputDom.select();
                        }
                    });
                    return false;
                });

                tableModel.where = {
                    wildcardSource: param.wildcardSource(),
                    termSource: param.termSource(),
                    actionId: currentAction() ? currentAction().id : "",
                    planId: modelId
                };
                tableModel.page.curr = param.curr;
                tableModel.page.limit = param.limit;

                tableIns = table.render(tableModel);

                table.on("tool(list-table)", function(obj) {
                    var data = obj.data;
                    if (obj.event === "item-fix") {
                        if (param.termSource() && param.termSource().trim()) {
                            window.open("/back/urlContent?parentId=" + encodeURIComponent(data._id) + "&targetUrl=" + encodeURIComponent(param.termSource()));
                        } else {
                            layer.alert("必须为精确搜索才可以定位超链接");
                        }
                    }
                });

                form.on("submit(search-submit)", function(data) {
                    var searchObjUpdate = {
                        where: {
                            wildcardSource: param.wildcardSource(),
                            termSource: param.termSource(),
                            actionId: currentAction() ? currentAction().id : "",
                            planId: modelId
                        },
                        page: {
                            curr: 1
                        }
                    };
                    tableIns.reload(searchObjUpdate);
                    return false;
                });
                /*form.on("submit(create-request)", function(data) {
                    router.navigate("security/roleCreate");
                    return false;
                });*/
            });
        }
    };
});